class User < ActiveRecord::Base
  has_one :contact
  has_many :wish_lists, :dependent => :destroy

  # Include default devise modules. Others available are:
  # :http_authenticatable, :token_authenticatable, :lockable, :timeoutable, :confirmable and :activatable
  devise :registerable, :database_authenticatable, :recoverable,
         :rememberable, :trackable, :validatable, :invitable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :roles

  ROLES = %w[role_admin role_supervisor role_administrative role_customer]

  def self.search_selector(search_email, page)
    search(search_email, page)
  end

  def self.search(search_email, page)
    items_per_page = count_record_per_page :users
    order = "email"

    conditions_clauses = []
    conditions_options = []
    if !search_email.nil? && search_email.size != 0
      conditions_clauses << "upper(email) like upper(?)"
      conditions_options << "%#{search_email}%"
    end
    conditions = [conditions_clauses.join(" AND "), conditions_options].flatten

    @localusers = User.paginate :per_page => items_per_page,:page => page, :conditions => conditions, :order => order
  end

  def role_symbols
    roles.map(&:to_sym)
  end

  def roles=(roles)
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
  end

  def roles
    ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
  end

  def role? role
    roles.include? role.to_s
  end
end
